﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CPPEI.ShareScreen.App.RD
{
    /// <summary>
    /// Interaction logic for RDWindow.xaml
    /// </summary>
    public partial class RDWindow : Window
    {
        private uint _targetClientID;
        private uint _roomID;
        private CPPEI.ShareScreen.ServerProxy.ServerProxyClient _proxy;

        public RDWindow( ServerProxy.ServerProxyClient proxy, uint targetClientID, uint roomID)
        {
            InitializeComponent();

            _proxy = proxy;
            _targetClientID = targetClientID;
            _roomID = roomID;

            CPPEI.Event.NCL.NCLEventBus.Register(this);
            CPPEI.ShareScreen.Event.UI.UIEventBus.Register(this);
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            // 发送断开远程桌面的请求
            CPPEI.ShareScreen.Event.NCL.NCLRDDisconnectEvent @event = new Event.NCL.NCLRDDisconnectEvent();
            @event.TargetClientID = _targetClientID;
            @event.RoomID = _roomID;
            CPPEI.Event.NCL.NCLEventBus.PublishAsync(@event);

            base.OnClosing(e);
        }


        protected override void OnClosed(EventArgs e)
        {
            CPPEI.ShareScreen.Event.UI.UIEventBus.Unregister(this);
            CPPEI.Event.NCL.NCLEventBus.Unregister(this);

            base.OnClosed(e);
        }

        public void SetImage(byte[] data)
        {
            this.Dispatcher.Invoke(() =>
            {
                BitmapImage imageSource = ByteArrayToBitmapImage(data);
                this._ctlImage.Source = imageSource;
            });
        }

        public static BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
        {
            BitmapImage bmp = null;
            try
            {
                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byteArray);
                bmp.EndInit();
            }
            catch
            {
                bmp = null;
            }
            return bmp;
        }
    }
}
